﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.DepartMent;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;

namespace SmartCity.BasicData.Api.Application.Handler.DepartMent
{
    public class GetDepartmentHandler : IRequestHandler<GetDepartMentCommand, ApiResult<List<DepartMentDTO>>>
    {
        private readonly IBaseRepository<DepartmentsModel> departRepo;
        private readonly IMapper mapper;

        public GetDepartmentHandler(IBaseRepository<DepartmentsModel> departRepo,IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<DepartMentDTO>>> Handle(GetDepartMentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartMentDTO>> result = new ApiResult<List<DepartMentDTO>>();
            result.Data = GetDepartMentTree();
            return Task.FromResult(result);
        }

        private List<DepartMentDTO> GetDepartMentTree(long parent=0) { 
        var lists = departRepo.GetAsync(x => x.ParentId == parent).Result;
            var deaprtmentDtoList = mapper.Map<List<DepartMentDTO>>(lists);
            deaprtmentDtoList.ForEach(d => {
                d.Childs = GetDepartMentTree(d.Id);
            });
            return deaprtmentDtoList;
        }
    }
}
